<?php


namespace App\Http\Controllers\Admin;
use App\Http\Controllers\BaseController;
use App\Models\MallFullReduction;
use App\Models\MallOrder;
use App\Models\MallOrderProduct;
use App\Services\MallOrderService;
use Illuminate\Http\Request;

class MallFullReductionController extends BaseController
{

    /**
     * 保存|修改
     * @param Request $request
     * @return mixed
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(Request $request) {
        $this->validate($request, [
            'merchant_id' => 'required',
            'amount' => 'required',
        ]);
        $input = $request->input();
        $id = \request("id");
        $exist_id = MallFullReduction::where('merchant_id', \request('merchant_id'))->value('id');
        if ($id) {
            if ($exist_id && ($id != $exist_id)) {
                return $this->failed("已经存在");
            }
            MallFullReduction::where('id', $id)->update($input);
        } else {
            if ($exist_id)
                return $this->failed("已经存在");

            $info = MallFullReduction::create($input);
            $id = $info->id;
        }
        return $this->success($id);
    }


    public function index(Request $request) {

        $fac_title = $request->input('fac_title');
        $list = MallFullReduction::withCertain('merchant', ['fac_title'])
            ->when($fac_title, function ($q) use($fac_title){
                $q->whereHas('merchant', function ($qt)  use($fac_title){
                    $qt->where('fac_title', 'like', '%'. $fac_title. '%');
                });
            })
            ->orderBy('id', 'desc')
            ->paginate(\request('per_page', 20));

        return $this->paginate($list);
    }

    public function info(Request $request)
    {
        $id = $request->input('id');
        $reduction = MallFullReduction::withCertain('merchant', ['fac_title'])->find($id);
        if (!$reduction)
            return $this->failed('不存在');
        return $this->success($reduction);
    }


    public function destroy(Request $request) {
        $this->validate($request, [
            'ids' => 'required'
        ]);
        $ids = $request->input('ids');
        $arr_id = explode(",", $ids);
        foreach ($arr_id as $id) {
            $info = MallFullReduction::find($id);
            if (!$info)
                return $this->failed('不存在');
            $info->delete();
        }
        return $this->success([]);
    }



}

